<?php

namespace App\ServicesNew\Impl;

use App\Entities\UserAddressEntity;
use App\Entities\UserAddressModel;
use App\ServicesNew\UserAddressService;

class UserAddressServiceImpl implements UserAddressService
{
    /**
     * @inheritDoc
     */
    public function getLastSetUserAddress(int $userId, int $cityId)
    {
        $userModel = UserAddressModel::where('user_id', '=', $userId)
            ->orderBy('created_at', 'desc')
            ->where('provinceid', $cityId)
            ->first();
        return is_null($userModel) ? null : new UserAddressEntity($userModel);
    }

    /**
     * @inheritDoc
     */
    public function getDefaultUserAddress(int $userId, int $cityId)
    {
        $userModel = UserAddressModel::where('user_id', '=', $userId)
            ->where('isdefault', '=', 1)
            ->where('provinceid', $cityId)
            ->first();

        return is_null($userModel) ? null : new UserAddressEntity($userModel);
    }

    /**
     * @inheritDoc
     */
    public function getSuitableUserAddress(int $userId, int $cityId)
    {
        $default = $this->getDefaultUserAddress($userId, $cityId);
        if (!is_null($default)) {
            return $default;
        }

        return $this->getLastSetUserAddress($userId, $cityId);
    }
}
